
import axios, {AxiosRequestConfig, AxiosResponse} from "axios";
import config from "@/utils/apiConfig";
import util from "@/utils/util";

// 环境的切换 export暴露给其它可引用
export let URLAPI:any = {
  mainUrl: config.mainUrl, //主工程1
  secUrl: config.secUrl || "", //次工程2
  fileUpUrl: config.fileUpUrl || "", //附件上传接口工程
  fileUrl: config.fileUrl || "", //附件查看地址（附件前缀）
};

// 获取CancelToken 有需要的话可以用source.cancel();取消其他请求
const CancelToken = axios.CancelToken,
  source = CancelToken.source();
let queueNum = 0;



// 创建axios实例
let http = axios.create({
  baseURL: axios.defaults.baseURL, //process.env.VUE_APP_API,
  timeout: 60 * 1000,
  withCredentials: false, // 不允许携带cookie
  //用于普通传参数
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
  }
});

// 请求拦截器
http.interceptors.request.use((config:AxiosRequestConfig) => {
    // 请求前显示全局loading
    queueNum += 1;

    util.htmlLoad();
    // 全局添加cancelToken
    config.cancelToken = source.token;
    return config;
  },
  err => {
    util.htmlCloseLoad();
    const error = err;
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use((response:AxiosResponse) => {
    const { status, data } = response
    // 全部请求完成后hide loading
    queueNum -= 1;
    if (queueNum === 0) {
      util.htmlCloseLoad();
    }

    if (status !== 200) {
      return data;
    } else {
      return data;
    }
  },
  error => {
    queueNum -= 1;
    if (queueNum === 0) {
      util.htmlCloseLoad();
    }
    const { response } = error
    // 这里处理错误的 http code or 服务器或后台报错
    if ( response.status === 404 || response.status === 500) {
      util.showMessage(`接口异常（${response.status}错误）`, 'error')
    } else if(error.toString().indexOf('timeout') > -1){
      util.showMessage('请求接口超时','error');
    }else {
      util.showMessage(`请求异常，请稍后再试!`, 'error')
    }
    return Promise.reject(response)
  }
);


/**
 * get方法，对应get请求
 * @param {String} urlType [请求的服务器]
 * @param {String} apiPath [请求的url接口地址]
 * @param {Object} paramsOrData [请求时携带的参数]
 */
export function GET(urlType:string, apiPath:string, paramsOrData:object) {
  let url = apiPath.indexOf("http://") > -1 ? apiPath : `${URLAPI[urlType] + apiPath}`;
  return http({
    method: "GET", url,
    params: paramsOrData,
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  });
}

/**
 * post方法，对应post请求
 * @param {String} urlType [请求的服务器]
 * @param {String} apiPath [请求的url接口地址]
 * @param {Object} paramsOrData [请求时携带的参数]
 */
export function POST(urlType:string, apiPath:string, paramsOrData:object) {
  let url = apiPath.indexOf("http://") > -1 ? apiPath : `${URLAPI[urlType] + apiPath}`;
  return http({ method: "POST", url, params: paramsOrData });
}
